package com.yitiao.socket.chatroom.bio;

import com.yitiao.socket.chatroom.CommonConst;
import lombok.Data;
import lombok.SneakyThrows;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

@Data
public class ChatServer {

    private ServerSocket server;

    private volatile ConcurrentHashMap<Integer, BufferedWriter> connectedClientMap;

    @SneakyThrows
    public ChatServer() {
        this.connectedClientMap = new ConcurrentHashMap<>();
    }

    @SneakyThrows
    public void addClient(Socket socket){
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        connectedClientMap.put(socket.getPort(),writer);
        System.out.printf("client [%s] has joined chat%n",socket.getPort());
    }

    public void removeClient(Integer port) throws IOException {
        if (port!=null){
            BufferedWriter writer = connectedClientMap.get(port);
            if (writer!=null){
                writer.close();
            }
            connectedClientMap.remove(port);
        }
        System.out.printf("client [%s] has left chat%n",port);
    }

    public void forwardMessage(Integer port ,String msg){
        connectedClientMap.forEach((key,value)->{
            if (!key.equals(port)){
                try {
                    value.write(msg+"\n");
                    value.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public synchronized void close() {
        if (server != null) {
            try {
                server.close();
                System.out.println("server has closed.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @SneakyThrows
    public void start(){
        server = new ServerSocket(CommonConst.PORT);
        while (true){
//            System.out.println("wait client connected...");
            Socket socket = server.accept();
            // 主线程开放一些功能供处理器使用，来处理一些逻辑
            new Thread(new ChatHandler(this,socket)).start();
        }
    }

    public static void main(String[] args) {
        ChatServer server = new ChatServer();
        server.start();
    }
}
